<template>
  <el-card class="video-result-card" shadow="hover">
    <template #header>
      <div class="card-header">
        <span>🎬 解析结果</span>
        <el-tag :type="getPlatformTagType(video.platform)" size="small">
          {{ getPlatformName(video.platform) }}
        </el-tag>
      </div>
    </template>

    <div class="video-content">
      <!-- 视频封面和基本信息 -->
      <div class="video-info">
        <div class="video-cover">
          <el-image
            :src="video.cover_url"
            fit="cover"
            class="cover-image"
            :preview-src-list="[video.cover_url]"
            loading="lazy"
          >
            <template #error>
              <div class="image-slot">
                <el-icon><Picture /></el-icon>
                <span>封面加载失败</span>
              </div>
            </template>
          </el-image>
          
          <!-- 时长标签 -->
          <div v-if="video.duration" class="duration-badge">
            {{ formatDuration(video.duration) }}
          </div>
        </div>

        <div class="video-details">
          <h3 class="video-title">{{ video.title }}</h3>
          <div class="video-meta">
            <div class="author-info">
              <el-icon><User /></el-icon>
              <span>{{ video.author }}</span>
            </div>
            
            <div v-if="video.create_time" class="create-time">
              <el-icon><Clock /></el-icon>
              <span>{{ formatTime(video.create_time) }}</span>
            </div>
          </div>

          <!-- 统计数据 -->
          <div class="video-stats">
            <div v-if="video.view_count" class="stat-item">
              <el-icon><View /></el-icon>
              <span>{{ formatNumber(video.view_count) }}</span>
            </div>
            
            <div v-if="video.like_count" class="stat-item">
              <el-icon><span>👍</span></el-icon>
              <span>{{ formatNumber(video.like_count) }}</span>
            </div>
            
            <div v-if="video.comment_count" class="stat-item">
              <el-icon><ChatLineRound /></el-icon>
              <span>{{ formatNumber(video.comment_count) }}</span>
            </div>
            
            <div v-if="video.share_count" class="stat-item">
              <el-icon><Share /></el-icon>
              <span>{{ formatNumber(video.share_count) }}</span>
            </div>
          </div>

          <!-- 视频描述 -->
          <div v-if="video.description && video.description !== video.title" class="video-description">
            <p>{{ video.description }}</p>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button
          type="primary"
          size="large"
          @click="handleDownload"
          :disabled="!video.download_url"
        >
          <el-icon><Download /></el-icon>
          下载视频
        </el-button>

        <el-button
          size="large"
          @click="copyVideoUrl"
        >
          <el-icon><CopyDocument /></el-icon>
          复制链接
        </el-button>

        <el-button
          size="large"
          @click="previewVideo"
          :disabled="!video.download_url"
        >
          <el-icon><VideoPlay /></el-icon>
          预览
        </el-button>

        <el-button
          size="large"
          @click="showDetails = !showDetails"
        >
          <el-icon><InfoFilled /></el-icon>
          {{ showDetails ? '隐藏' : '详情' }}
        </el-button>
      </div>

      <!-- 详细信息 -->
      <el-collapse-transition>
        <div v-show="showDetails" class="video-details-panel">
          <el-descriptions title="详细信息" :column="2" border>
            <el-descriptions-item label="视频ID">
              <el-text class="mono-text">{{ video.id }}</el-text>
            </el-descriptions-item>
            
            <el-descriptions-item label="平台">
              {{ getPlatformName(video.platform) }}
            </el-descriptions-item>
            
            <el-descriptions-item label="作者ID" v-if="video.author_id">
              <el-text class="mono-text">{{ video.author_id }}</el-text>
            </el-descriptions-item>
            
            <el-descriptions-item label="时长" v-if="video.duration">
              {{ formatDuration(video.duration) }}
            </el-descriptions-item>
            
            <el-descriptions-item label="下载链接" span="2">
              <el-input
                :value="video.download_url"
                readonly
                class="url-input"
              >
                <template #append>
                  <el-button @click="copyText(video.download_url)">
                    <el-icon><CopyDocument /></el-icon>
                  </el-button>
                </template>
              </el-input>
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </el-collapse-transition>
    </div>

    <!-- 视频预览对话框 -->
    <el-dialog
      v-model="showPreview"
      title="视频预览"
      width="70%"
      :close-on-click-modal="true"
    >
      <div class="video-preview">
        <video
          v-if="showPreview"
          :src="video.download_url"
          controls
          preload="metadata"
          class="preview-video"
          @error="handleVideoError"
        >
          您的浏览器不支持视频播放
        </video>
      </div>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Picture,
  User,
  Clock,
  View,
  ChatLineRound,
  Share,
  Download,
  CopyDocument,
  VideoPlay,
  InfoFilled
} from '@element-plus/icons-vue'
import { formatNumber, formatDuration } from '@/utils/format'
import type { VideoInfo } from '@/types/api'

// 接收父组件传递的视频信息
interface Props {
  video: VideoInfo
}

const props = defineProps<Props>()

// 定义事件
const emit = defineEmits<{
  download: [video: VideoInfo]
}>()

// 响应式数据
const showDetails = ref(false)
const showPreview = ref(false)

// 获取平台名称
const getPlatformName = (platform: string): string => {
  const platformNames: Record<string, string> = {
    douyin: '抖音',
    tiktok: 'TikTok',
    bilibili: '哔哩哔哩'
  }
  return platformNames[platform] || platform
}

// 获取平台标签类型
const getPlatformTagType = (platform: string): string => {
  const tagTypes: Record<string, string> = {
    douyin: 'danger',
    tiktok: 'warning',
    bilibili: 'primary'
  }
  return tagTypes[platform] || 'info'
}

// 格式化时间
const formatTime = (timestamp: string): string => {
  try {
    const date = new Date(parseInt(timestamp) * 1000)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch {
    return timestamp
  }
}

// 下载视频
const handleDownload = () => {
  // 使用original_url或者download_url作为源URL
  const sourceUrl = props.video.original_url || props.video.download_url
  if (!sourceUrl) {
    ElMessage.error('无可用的视频链接')
    return
  }
  
  // 构建下载API URL
  const downloadUrl = new URL('/api/v1/download', window.location.origin)
  downloadUrl.searchParams.set('url', sourceUrl)
  downloadUrl.searchParams.set('with_watermark', 'false')
  downloadUrl.searchParams.set('prefix', 'true')
  
  // 创建隐藏的下载链接并触发下载
  const link = document.createElement('a')
  link.href = downloadUrl.toString()
  link.style.display = 'none'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  
  ElMessage.success('开始下载视频...')
}

// 复制视频链接
const copyVideoUrl = async () => {
  try {
    await copyText(props.video.download_url)
  } catch (error) {
    ElMessage.error('复制失败，请手动复制')
  }
}

// 复制文本到剪贴板
const copyText = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('已复制到剪贴板')
  } catch (error) {
    // 降级方案
    const textArea = document.createElement('textarea')
    textArea.value = text
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
    ElMessage.success('已复制到剪贴板')
  }
}

// 预览视频
const previewVideo = () => {
  if (!props.video.download_url) {
    ElMessage.warning('暂无可预览的视频链接')
    return
  }
  showPreview.value = true
}

// 处理视频加载错误
const handleVideoError = () => {
  ElMessage.error('视频加载失败，可能需要特殊播放器或下载后观看')
}
</script>

<style scoped>
.video-result-card {
  margin: 20px 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.video-content {
  padding: 10px;
}

.video-info {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.video-cover {
  position: relative;
  flex-shrink: 0;
  width: 200px;
  height: 150px;
}

.cover-image {
  width: 100%;
  height: 100%;
  border-radius: 8px;
  overflow: hidden;
}

.image-slot {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 14px;
}

.duration-badge {
  position: absolute;
  bottom: 8px;
  right: 8px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.video-details {
  flex: 1;
}

.video-title {
  margin: 0 0 10px 0;
  color: #303133;
  line-height: 1.4;
  word-break: break-word;
}

.video-meta {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
  color: #606266;
  font-size: 14px;
}

.video-meta > div {
  display: flex;
  align-items: center;
  gap: 4px;
}

.video-stats {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #909399;
  font-size: 14px;
}

.video-description {
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
  max-height: 60px;
  overflow: hidden;
}

.action-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  margin: 20px 0;
}

.video-details-panel {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.mono-text {
  font-family: 'Courier New', monospace;
  font-size: 12px;
}

.url-input {
  font-family: 'Courier New', monospace;
  font-size: 12px;
}

.video-preview {
  text-align: center;
}

.preview-video {
  max-width: 100%;
  max-height: 60vh;
  border-radius: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .video-info {
    flex-direction: column;
  }
  
  .video-cover {
    width: 100%;
    height: 200px;
  }
  
  .video-meta {
    flex-direction: column;
    gap: 8px;
  }
  
  .video-stats {
    justify-content: space-between;
  }
  
  .action-buttons {
    justify-content: center;
  }
  
  .action-buttons .el-button {
    flex: 1;
    min-width: 80px;
  }
}

/* 小屏幕优化 */
@media (max-width: 480px) {
  .video-stats {
    flex-direction: column;
    gap: 10px;
  }
  
  .action-buttons {
    flex-direction: column;
  }
}
</style>